package cn.sx.guoxd.springboot.security;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()//配置权限
                .antMatchers("/swagger-resources/**", "/swagger-ui.html", "/v2/api-docs", "/webjars/**","/api/**").permitAll()
                .anyRequest().authenticated()//任意请求需要登录
                .and()
                .formLogin()//开启formLogin默认配置
                .loginPage("/login/auth")//请求时未登录跳转接口
                .failureUrl("/login/fail")//用户密码错误跳转接口
                .defaultSuccessUrl("/login/success", true)//登录成功跳转接口
                .loginProcessingUrl("/login")//post登录接口，登录验证由系统实现
                .usernameParameter("username")    //要认证的用户参数名，默认username
                .passwordParameter("password").permitAll()    //要认证的密码参数名，默认password
                .and()
                .logout()//配置注销
                .logoutUrl("/logout")//注销接口
                .logoutSuccessUrl("/login/logout").permitAll()//注销成功跳转接口
                .deleteCookies("myCookie") //删除自定义的cookie
                .and()
                .csrf().disable();           //禁用csrf
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123").authorities("admin")
                .and()
                .withUser("bgj").password("456").authorities("user")
                .and().passwordEncoder(NoOpPasswordEncoder.getInstance());

/*
        auth.jdbcAuthentication().dataSource(datasource)
                .usersByUsernameQuery("select username,password,enabled from users where username = ?")
                .authoritiesByUsernameQuery("select username,authority from authorities where username = ?")
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
*/

    }
}